from django.shortcuts import render, redirect
from manage_worker import models
from manage_worker.utills.form import PrettyEditNumModelForm, PrettyNumModelForm
from manage_worker.utills.pagination import Pagination


def pretty_list(request):
    '''靓号列表'''
    # 筛选功能
    # 定义一个空列表
    data_list = {}
    # 取前端传过来的字段 q,如果取不到自动为空，语法记住就好get('sth', 'default_value默认值')
    search_data = request.GET.get('q', '')
    # 如果前端传过来的值
    if search_data:
        # 把值存入列表中
        data_list['mobile__contains'] = search_data
    # filter()方法支持传入一个列表筛选，列表名之前需要加 ** ，如果列表为空，就会筛选所有的
    queryset = models.PrettyNum.objects.filter(**data_list).order_by('-level')

    page_object = Pagination(request, queryset=queryset)
    context = {
        'search_data': search_data,
        'queryset': page_object.page_queryset,  # 分完页的数据
        'page_string': page_object.html()  # 页码
    }

    return render(request, 'pretty_list.html', context)


def pretty_add(request):
    if request.method == 'GET':
        form = PrettyNumModelForm()
        return render(request, 'change.html', {'form': form})
    form = PrettyNumModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'change.html', {'form': form})


def pretty_edit(request, id):
    '''
    编辑靓号
    :param request:
    :param id: 靓号id
    :return:
    '''
    # 从数据库中根据id取出数据
    row_object = models.PrettyNum.objects.filter(id=id).first()
    if request.method == 'GET':
        form = PrettyEditNumModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {'form': form})

    # 如果不加instance=row_object就会在表中新增一条数据，加了就会在原先得数据中更改
    form = PrettyEditNumModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')
    return render(request, 'pretty_edit.html', {'form': form})


def pretty_delete(request):
    id = request.GET.get('id')
    models.PrettyNum.objects.filter(id=id).delete()
    return redirect('/pretty/list/')
